
import ctypes, os,sys, signal, posix_ipc,time,mmap, fcntl, numpy
from threading import Thread

ll = ctypes.cdll.LoadLibrary   
lib_video = ll("./libHiApp.so")
lib_common = ll("../libs/libHiRTPCommon.so")


FLAG = 14520

def start_video():
    rtsp = bytes("rtmp://58.200.131.2:1935/livetv/gxtv","utf8")
    id = lib_video.hi_video_image_share_start(rtsp, 60001, 1920, 1080, 14520)
    print("call hi_video_image_share_start, return {0}".format(id))

from multiprocessing import Manager, Process, Queue, Value

sempty = None
sfull = None
is_exit = False

share_path = "/tmp/hi/video_test_" + str(FLAG) + "_bgr"
image_queue = Queue()

os.system('rm bmp/*')
os.system('rm ' + "/tmp/hi/video_test_" + str(FLAG) + "*")

def sigint_handler(signum, frame):
    global sempty
    global sfull
    global is_exit
    global IsExit
    if is_exit == True:
        exit(-1)
        return
    is_exit = True
    if sempty != None:
        sempty.close()
    if sfull != None:
        sfull.close()

    print('catched interrupt signal!')
    time.sleep(1)
    exit(-1)

signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGHUP, sigint_handler)
signal.signal(signal.SIGTERM, sigint_handler)
        
def pic_receive_thread():
    shape =  (1920, 1080, 3)

    interval = 1.0 / 25
    quit = None
    while not os.path.exists(share_path):
        time.sleep(0.3)
    prefix = share_path
    prefix = "/" + prefix.replace("/", ".")
    empty_key = prefix + ".empty"
    full_key = prefix + ".full"
    sempty = posix_ipc.Semaphore(empty_key, posix_ipc.O_CREAT, initial_value=1)
    sfull = posix_ipc.Semaphore(full_key, posix_ipc.O_CREAT, initial_value=0)
    print(empty_key)
    print(full_key)
    global is_exit

    try:
        with open(share_path, "r+b") as f:
            mm = mmap.mmap(f.fileno(), 0)
            while is_exit != True:
                try:
                    res = sfull.acquire(0.2)
                except Exception as e:
                    print('acquire full error.' + str(e))
                    continue
                fcntl.flock(f, fcntl.LOCK_EX)
                img = numpy.ndarray(shape=shape, dtype=numpy.uint8, buffer=mm).copy()
                fcntl.flock(f, fcntl.LOCK_UN)
                image_queue.put((0, img))
                sempty.release()
    except Exception as e:
        print('receive pic exception:' + str(e))   
        sempty.release()
        image_queue.put((None, str(e)))
    print('pic recevie quit')    
    sempty.close()
    sfull.close()
    sempty = None
    sfull = None
      
def pic_save_thread():
    save_index = 0
    global is_exit
    while is_exit != True:
        sn, img = image_queue.get()
        '''
        if save_index < 100:        
            print(str(img.shape) + ";" + str(img.dtype) + ";" )
            cv2.imwrite("bmp/" + str(save_index) + '.bmp', img)
            print("save index:" + str(save_index) + ";" + "bmp/" + str(save_index) + '.bmp')
        else:
            is_exit = True
            print("exit")
        '''
        try:
            char_p_test = bytes("./bmp/" + str(save_index % 100) + '.bmp',"utf8")
            lib_common.hi_saveBmp(char_p_test, img.tobytes(), 1920, 1080)
            save_index = save_index + 1
            print('save pic success:', char_p_test)    
        except Exception as e:
            print('save pic exception:' + str(e))    
    print('pic save quit')    


start_video()
receive_thread = Thread(target=pic_receive_thread)
save_thread = Thread(target=pic_save_thread)
save_thread.start()
receive_thread.start()
save_thread.join()
receive_thread.join()

print('DataTransport quit')
